/**
 * TaskMaster v1 - Authentication Store
 * AceFlow v3.0 - Implementation Phase
 */

import { defineStore } from 'pinia'
import axios from 'axios'
import router from '../router'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    user: null,
    token: localStorage.getItem('token') || null,
    isAuthenticated: !!localStorage.getItem('token')
  }),

  getters: {
    getUser: (state) => state.user,
    getToken: (state) => state.token,
    isLoggedIn: (state) => state.isAuthenticated
  },

  actions: {
    async login(credentials) {
      try {
        const response = await axios.post('/api/auth/login', credentials)

        if (response.data.success) {
          this.token = response.data.token
          this.isAuthenticated = true

          // Store token in localStorage
          localStorage.setItem('token', this.token)

          // Set axios default authorization header
          axios.defaults.headers.common['Authorization'] = `Bearer ${this.token}`

          // Fetch user info
          await this.fetchUser()

          // Navigate to tasks page
          router.push('/')

          return { success: true, message: response.data.message }
        } else {
          return { success: false, message: response.data.message }
        }
      } catch (error) {
        const message = error.response?.data?.detail || '登录失败'
        return { success: false, message }
      }
    },

    async register(userData) {
      try {
        const response = await axios.post('/api/auth/register', userData)

        if (response.data.success) {
          // Auto login after successful registration
          return await this.login({
            username: userData.username,
            password: userData.password
          })
        } else {
          return { success: false, message: response.data.message }
        }
      } catch (error) {
        const message = error.response?.data?.detail || '注册失败'
        return { success: false, message }
      }
    },

    async fetchUser() {
      try {
        const response = await axios.get('/api/auth/me')
        this.user = response.data
        return { success: true, user: response.data }
      } catch (error) {
        console.error('Failed to fetch user:', error)
        return { success: false, message: '获取用户信息失败' }
      }
    },

    logout() {
      // Clear state
      this.user = null
      this.token = null
      this.isAuthenticated = false

      // Remove from localStorage
      localStorage.removeItem('token')

      // Remove axios authorization header
      delete axios.defaults.headers.common['Authorization']

      // Navigate to login
      router.push('/login')
    },

    async initializeAuth() {
      const token = localStorage.getItem('token')
      if (token) {
        this.token = token
        this.isAuthenticated = true
        axios.defaults.headers.common['Authorization'] = `Bearer ${token}`

        // Validate token by fetching user info
        const result = await this.fetchUser()
        if (!result.success) {
          // Token is invalid, logout
          console.log('Token validation failed, logging out...')
          this.logout()
          return false
        }
        return true
      }
      return false
    }
  }
})
